#用于访问 中国比特币 现货 rest api

from lib.utilChbtc import api_call, sort_and_format
from lib.settings import CHBTC_API_URL
import urllib.request
import json
import config

'''
中国比特币现货交易
'''
class Chbtc(object):
    def __init__(self):  # url使用CHBTC_API_URL['host']
        self.__apikey = config.CHBTC_API_KEY
        self.__secretkey = config.CHBTC_SECRET_TOKEN
        self.fee = CHBTC_API_URL['fee']

        self.btc_free = 0.0  # 账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0  # 买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0

    '''
    更新OKCOIN现货市场深度信息
    '''
    def update_depth(self):
        try:
            response = urllib.request.urlopen(CHBTC_API_URL['depth'], timeout=1)
            result = json.loads(response.read().decode('utf-8'))

            if result and 'code' in result:  # result不为空，且有错误代码的存在；为空的原因可能是请求超时
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False
            if not result:  # result为空
                self.bid = 0.0
                self.bid_volume = 0.0
                self.ask = 0.0
                self.ask_volume = 0.0
                return False

            self.bid = float(sort_and_format(result['bids'], True)[0]['price'])
            self.bid_volume = float(sort_and_format(result['bids'], True)[0]['volume'])
            self.ask = float(sort_and_format(result['asks'], False)[0]['price'])
            self.ask_volume = float(sort_and_format(result['asks'], False)[0]['volume'])
            return True
        except Exception as e:
            self.bid = 0.0
            self.bid_volume = 0.0
            self.ask = 0.0
            self.ask_volume = 0.0
            print(e)
            return False


    '''
    更新账户资金信息
    '''
    def update_accountInfo(self):
        try:
            params = "method=getAccountInfo&accesskey=" + self.__apikey
            path = CHBTC_API_URL['account_info']

            response = api_call(self.__secretkey, path, params)

            if response and 'code' in response:
                self.btc_free = 0
                self.btc_frozen = 0
                self.cny_free = 0
                self.cny_frozen = 0
                return False
            if not response:
                self.btc_free = 0
                self.btc_frozen = 0
                self.cny_free = 0
                self.cny_frozen = 0
                return False

            self.btc_free = float(response['result']['balance']['BTC']['amount'])
            self.btc_frozen = float(response['result']['frozen']['BTC']['amount'])
            self.cny_free = float(response['result']['balance']['CNY']['amount'])
            self.cny_frozen = float(response['result']['frozen']['CNY']['amount'])
            return True

        except Exception as e:
            self.btc_free = 0
            self.btc_frozen = 0
            self.cny_free = 0
            self.cny_frozen = 0
            print(e)
            return False


    '''
    买入比特币
    '''
    def buy(self, price, amount):
        try:
            params = "method=order&accesskey=%s&price=%f&amount=%f&tradeType=1&currency=btc_cny" % (self.__apikey, price, amount)
            path = CHBTC_API_URL['trade']

            response = api_call(self.__secretkey, path, params)
            if response and response['code']!=1000:
                return False
            if not response:
                return False

            return str(response['id'])

        except Exception as e:
            print(e)
            return False


    '''
    卖出比特币
    '''
    def sell(self, price, amount):
        try:
            params = "method=order&accesskey=%s&price=%f&amount=%f&tradeType=0&currency=btc_cny" % (self.__apikey, price, amount)
            path = CHBTC_API_URL['trade']

            response = api_call(self.__secretkey, path, params)
            if response and response['code'] != 1000:
                return False
            if not response:
                return False

            return str(response['id'])

        except Exception as e:
            print(e)
            return False


    '''
    现货订单信息查询
    '''
    def order_info(self, orderId):
        try:
            if orderId == False:
                return False
            params = "method=getOrder&accesskey=%s&id=%s&currency=btc_cny" % (self.__apikey, orderId)
            path = CHBTC_API_URL['order_info']

            response = api_call(self.__secretkey, path, params)
            if response and 'code' in response:
                return False
            if not response:
                return False
            if response['status'] in (0, 3):
                return 'cancelable'
            else:
                return 'ircancelable'

        except Exception as e:
            print(e)
            return False


    '''
    查询当前未成交订单
    '''
    def get_orders(self):
        try:
            params = "method=getUnfinishedOrdersIgnoreTradeType&accesskey=%s&currency=btc_cny&pageIndex=1&pageSize=20" % (self.__apikey)
            path = CHBTC_API_URL['get_orders']

            response = api_call(self.__secretkey, path, params)
            if response and 'code' in response:
                return False
            if not response:
                return False

            return response

        except Exception as e:
            print(e)
            return False


    '''
    取消订单
    '''
    def cancel_order(self, orderId):
        try:
            if orderId == False:
                return False
            params = "method=cancelOrder&accesskey=%s&id=%s&currency=btc_cny" % (self.__apikey, orderId)
            path = CHBTC_API_URL['cancelOrder']
            response = api_call(self.__secretkey, path, params)
            if response and response['code']!=1000:
                return False
            if not response:
                return False

            return True

        except Exception as e:
            print(e)
            return False


    '''
    取消所有当前所有未成交订单
    '''
    def cancel_all(self):
        try:
            response = self.get_orders()
            if response==False:
                return False
            for order in response:
                self.cancel_order(order['id'])
        except Exception as e:
            print(e)
            return False
